package com.maixy.paydemo.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.maixy.paydemo.common.Constant;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AlipayController
 * @Description TODO
 * @Date 2021/4/21 11:01
 * @Author maixy
 */
@RestController
@RequestMapping("/alipay")
public class AlipayController {

    //http://localhost:10005/alipay/goAlipay?orderNo=111&totalPrice=200&itemString=123321
    //前往支付宝沙箱网关进行支付
    @RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String goAlipay(@RequestParam("orderNo") String orderNo, @RequestParam("totalPrice") String totalPrice,
                           @RequestParam("itemString") String itemString, HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse) throws Exception {
        System.out.println(orderNo);
        System.out.println(totalPrice);
        System.out.println(itemString);
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(Constant.GATEWAY_URL, Constant.APP_ID, Constant.APP_PRIVATE_KEY, Constant.FORMAT, Constant.CHARSET, Constant.ALIPAY_PUBLIC_KEY, Constant.SIGN_TYPE);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(Constant.RETURN_URL);//同步
        alipayRequest.setNotifyUrl(Constant.NOTIFY_URL);//异步

        String out_trade_no = orderNo; //订单号
        String total_amount = totalPrice;//付款金额，必填
        String subject = "【半藏商城】"+itemString;  //订单名称，必填
        String body = "这是商品描述";//商品描述，可空
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";
        if(null!=total_amount) { //支付金额不等于空
            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"timeout_express\":\""+ timeout_express +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        }
        return "error/error_5xx";
    }
}
